package org.example.dyscript.dynamicscript;

import org.springframework.expression.Expression;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.ParserContext;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;

import java.util.Map;

public class SpELRule implements Rule {

  private final static ExpressionParser parser = new SpelExpressionParser();


  Expression executeExpression;
  Expression evaluateExpression;

  String executeScript = "#{ #ali_score > 100 && #wx_score < 450 && ! #pd_living_province.contains(\"乌克兰\") "
      + "&& #pd_census_province.contains(\"吉尔吉斯斯坦\") }";

  String evaluateScript = "#{ #age > 18 && #vip.contains(\"vip\") }";

  public SpELRule() {
    executeExpression = parser.parseExpression(executeScript, ParserContext.TEMPLATE_EXPRESSION);
    evaluateExpression = parser.parseExpression(evaluateScript, ParserContext.TEMPLATE_EXPRESSION);
  }

  @Override
  public boolean execute(Map<String, Object> parameters) {
    StandardEvaluationContext context = new StandardEvaluationContext();
    context.setVariables(parameters);
    return executeExpression.getValue(context, Boolean.class);
  }

  @Override
  public boolean evaluate(Map<String, Object> parameters) {
    StandardEvaluationContext context = new StandardEvaluationContext();
    context.setVariables(parameters);
    return evaluateExpression.getValue(context, Boolean.class);
  }
}
